/*
 * Copyright (C) 2013 Mestrelab Research S.L. All rights reserved.
 *
 * This file is part of the Mnova scripting toolkit.
 *
 * Authorized users of MNova Software may use this file freely, but this file is provided AS IS
 * with NO WARRANTY OF ANY KIND, INCLUDING THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE.
 */

/*jslint plusplus: true, indent: 4*/
/*global Application, Molecule, NMRAssignments, qsTr, MessageBox, print, ProgressDialog, MnUi*/

function batchUpdatePredictionDB() {
	'use strict';
	var dbLetter,
		solvent,
		nucleus,
		i,
		curMol,
		isValidMolecule,
		molItems = Application.mainWindow.activeDocument.docItems.filter(function (aItem) { return aItem && aItem.name === 'Molecule'; }),
		ui = Application.loadUiFile("ricares:batchUpdatePredictionDB.ui"),
		progressDialog,
		labelTemplate = qsTr('Sending to Prediction DB (%1 of %2)');

	if (!molItems.length) {
		MessageBox.critical(qsTr('No molecules in document.'));
		return 1;
	}
	if (ui !== undefined) {
		ui.widgets.fNucleusComboBox.items = ['1H', '13C', '11B', '15N', '17O', '19F', '29Si', '31P'];
		ui.widgets.fDbLetterComboBox.items = ['N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
		ui.widgets.fSolventComboBox.items = ['Chloroform', 'DMSO'];
		if (ui.exec()) {
			nucleus = ui.widgets.fNucleusComboBox.currentText;
			dbLetter = ui.widgets.fDbLetterComboBox.currentText;
			solvent = ui.widgets.fSolventComboBox.currentText;
			isValidMolecule = function (aMolecule) {
				var mol = new Molecule(aMolecule),
					assignObj,
					element = nucleus.replace(/\d+/, '');
				if (mol.isValid) {
					assignObj = new NMRAssignments(mol);
					return assignObj.hasAssignments(element);
				}
				return false;
			};
			molItems = molItems.filter(isValidMolecule);
			if (!molItems.length) {
				MessageBox.critical(qsTr('The selected molecules has no assignments for %1.'.arg(nucleus)));
				return 1;
			}
			progressDialog = new ProgressDialog();
			progressDialog.minimum = 0;
			progressDialog.maximum = molItems.length;
			progressDialog.value = 0;
			progressDialog.labelText = labelTemplate.arg(1).arg(molItems.length);
			progressDialog.visible = true;
			Application.NMRPredictor.silentMode = true;
			for (i = 0; i < molItems.length; ++i) {
				progressDialog.value = i;
				progressDialog.labelText = labelTemplate.arg(i + 1).arg(molItems.length);
				curMol = new Molecule(molItems[i]);
				Application.NMRPredictor.updateUserDB(nucleus, curMol, dbLetter, solvent);
				if (progressDialog.wasCancelled || !progressDialog.visible) {
					break;
				}
			}
			progressDialog.visible = false;
			Application.NMRPredictor.silentMode = false;
		}
	}
}

if (this.MnUi && MnUi.scripts_nmr) {
	MnUi.scripts_nmr.scripts_nmr_BatchUpdatePredictionDB = batchUpdatePredictionDB;
}
